/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cnam.mobileshopping.ejb.list;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.cnam.mobileShopping.entity.Constants;
import org.cnam.mobileShopping.entity.MList;
import org.cnam.mobileShopping.entity.Product;
import org.cnam.mobileShopping.entity.Productlist;
import org.cnam.mobileShopping.entity.User;
import org.cnam.mobileShopping.entity.Userlist;
import org.cnam.mobileshopping.ejb.product.ProductLocal;
import org.cnam.mobileshopping.ejb.user.UserLocal;

/**
 *
 * @author Administrateur
 */
@Stateless(mappedName="ejb/mobileshopping/mlist")
@Local(MListLocal.class)
@Remote(MListRemote.class)
public class MListBean implements MListLocal, MListRemote{

    @PersistenceContext(unitName="mobileshopping-corePU")
    EntityManager entityManager;
    
    @EJB(name="ejb/mobileshopping/product")
    ProductLocal productLocal;
    
    @EJB(mappedName="ejb/mobileshopping/user")
    UserLocal userLocal;
    
    @Override
    public List<MList> getLists(Integer userId) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public MList getList(Integer listId) {
        if(listId != null) {
            List<MList> results = entityManager.createNamedQuery("MList.findByMListid").setParameter("listid",listId).getResultList();
            if(results != null && results.size() == 1){
                return results.get(0);
            } else {
                return null;
            }
        } else {
            throw new NullPointerException("The list not exist");
        }
    }
    
  
    public MList getListByCommonId(String commonlistId) {
        if(commonlistId != null) {
            List<MList> results = entityManager.createNamedQuery("MList.findByCommonMListid").setParameter("commonlistid",commonlistId).getResultList();
            if(results != null && results.size() == 1){
                return results.get(0);
            } else {
                return null;
            }
        } else {
            throw new NullPointerException("The list not exist");
        }
    }

    
    public Productlist addProductInList(String commonlistId, Integer productId, 
            Integer userId, Integer quantity, String commonid, int version) {
        if (productId != null && commonlistId != null && userId != null){
            MList list = getListByCommonId(commonlistId);
            Product product = productLocal.getProduct(productId);
            User user = userLocal.getUserById(userId);
            if(list != null && product != null && userId != null) {
                // recuperation de la liste de produit associée à la liste
                List<Productlist> productsList = getProductsList(list.getMlistid());
                if(productsList == null) {
                   productsList = new ArrayList<Productlist>();
                }
                // creation du couple liste/produit
                Productlist productlist = new Productlist();
                productlist.setProductid(product);
                productlist.setUserid(user);
                productlist.setQuantity(quantity);
                productlist.setStatusid(Constants.statusProductInList.NOTBUILD.getId());
                productlist.setLastupdatedatetime(new Date());
                productlist.setMlistid(list);
                productlist.setCommonid(commonid);
                productlist.setVersion(version + 1);
                entityManager.persist(productlist);
                
                return productlist;
            } else {
                throw new NullPointerException("The list not exist OR product not exist OR userId is null"); 
            }
         } else {
             throw new NullPointerException("The list not exist OR product not exist OR userId is null"); 
           }
    }
 
    @Override
    public MList addList(Integer userId, String label, String commonid, Short statusid, int version) {
        User user = userLocal.getUserById(userId);
        
        if(userId != null && label != null && user != null && commonid != null) {
            Calendar cal = Calendar.getInstance();
            MList list = new MList();
            list.setLabel(label);  
            list.setCreatedatetime(cal.getTime());
            list.setStatus(statusid);
            list.setCommonid(commonid);
            list.setVersion(version);
            //enregistrement de la liste
            entityManager.persist(list);
            // creation de la relation proprietaire
            Userlist userslist = new Userlist();
            
            userslist.setMlistid(list);
            userslist.setUserid(user);
            userslist.setStatus(Constants.statusUser.OWNER.getId());
            
            //enregistrement du propriétaire de la liste
            entityManager.persist(userslist);
            return list;
        } else {
             throw new NullPointerException("The userId OR label is null"); 
        }
    }

    public List<Userlist> getUsersList(Integer listId) {
        if (listId != null){
             MList list = getList(listId);
            return entityManager.createNamedQuery("Userlist.findByUsermlistid").setParameter("mlistid", list).getResultList();                        
         } else {
             throw new NullPointerException("The list not exist"); 
           }
    }
    
    public List<Productlist> getProductsList(Integer listid) {
        if (listid != null){
            MList list = getList(listid);
            if(list != null) {
            return entityManager.createNamedQuery("Productlist.findByMlistid").setParameter("mlistid", list).getResultList();                        
            }
         } 
         throw new NullPointerException("The list not exist"); 
    }
    
   public List<Productlist> getProductsListByCommonId(String commonlistid) {
        if (commonlistid != null){
            MList list = getListByCommonId(commonlistid);
            if(list != null) {
            return entityManager.createNamedQuery("Productlist.findByMlistid").setParameter("mlistid", list).getResultList();                        
            }
         } 
         throw new NullPointerException("The list not exist"); 
    }

    @Override
    public Productlist updateProductInList(String commonProductListeId, Integer userId, Integer quantity, 
                int status, int version) {
       if(commonProductListeId != null /*&& userId != null && quantity != null*/) {
          Productlist pl = getProductListByCommonId(commonProductListeId);
          if (pl != null) {
             if(quantity != null) {
              pl.setQuantity(quantity);
             }
             if(status > 0) {
                 pl.setStatusid(status);
             }
             pl.setVersion(version + 1);
              entityManager.merge(pl);
              return pl;
          } else {
               throw new NullPointerException("The productListeId not exist"); 
          }
       } else {
            throw new NullPointerException("The productListeId not exist"); 
       }
      
       
    } 
    
    private Productlist getProductList(Integer productListId) {
        List<Productlist> results = entityManager.createNamedQuery("Productlist.findByProductlistid").setParameter("productlistid",productListId).getResultList();
            if(results != null && results.size() == 1){
                return results.get(0);
            } else {
                return null;
            }
        
    }
    
     private Productlist getProductListByCommonId(String commonproductListId) {
        List<Productlist> results = entityManager.createNamedQuery("Productlist.findByCommonProductlistid").setParameter("commonproductlistid",commonproductListId).getResultList();
            if(results != null && results.size() == 1){
                return results.get(0);
            } else {
                return null;
            }
    }

    @Override
    public void deleteProductInList(String commonproductListeId, Integer userId) {
        if (commonproductListeId != null) {
          Productlist pl = getProductListByCommonId(commonproductListeId);
          if (pl != null) {
              entityManager.remove(pl);
          } else {
               throw new NullPointerException("The productListeId not exist");
          }
       } else {
            throw new NullPointerException("The productListeId not exist");
        }
    }

    @Override
    public MList updateList(String commonlistId, String label, Short statusid, int version) {
        MList list = null;
        if(commonlistId != null) {
           list = getListByCommonId(commonlistId);
           if(list != null) {
               if(label != null) {
                   list.setLabel(label);
               }
               if(statusid != null) {
                   list.setStatus(statusid);
               }
               list.setVersion(version);
               entityManager.merge(list);
           }
       }
       return list;
    }

    @Override
    public void deleteList(String commonlistId, Integer userId) {
        if(commonlistId != null) {
            MList list = getListByCommonId(commonlistId);
            if(list != null) {
                entityManager.remove(list);
            }
        }
    }

    @Override
    public List<MList> getListsForUser(Integer userId) {
         List<MList> list = null;
        if(userId != null){
            User u = userLocal.getUserById(userId);
            List<Userlist> userlist =  entityManager.createNamedQuery("Userlist.findByUserid").setParameter("userid",u).getResultList();
            if(userlist != null) {
               list = new ArrayList<MList>();
                for(Userlist ul : userlist) {
                    list.add(ul.getMlistid());
                }
            }
        }
        return list;
    }

    @Override
    public void sharedist(Integer userId, String commonlistid) {
      if(userId != null && commonlistid != null) {
          MList list = getListByCommonId(commonlistid);
          User collaborator = userLocal.getUserById(userId);
          if(list != null && collaborator != null) {
              List<MList> mlists = getListsForUser(userId);
             // if(mlists == null || (mlists != null && !mlists.contains(list))) {
                 Userlist userlist = new Userlist();
                userlist.setMlistid(list);
                userlist.setUserid(collaborator);
                userlist.setStatus(Constants.statusUser.COLLAB.getId());
                    entityManager.persist(userlist);
              //}
             
          }
      }
    }
}
